﻿using System;
using System.Web.Mvc;
using SlamCms.Common;

namespace SlamCms.Web.Mvc
{
	public class RedirectToRefererResult : ActionResult
	{
		protected string defaultUrl { get; set; }
		public static string DefaultUrl = "/";

		public RedirectToRefererResult() : this(null)
		{
		}

		public RedirectToRefererResult(string defaultUrl)
		{
			this.defaultUrl = defaultUrl;
		}

		public override void ExecuteResult(ControllerContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");

			if (context.IsChildAction)
				throw new InvalidOperationException("Cannot use redirect in a child action.");

			var url = string.Empty;

			// use returnUrl
			var returnUrl = context.RequestContext.HttpContext.Request["returnUrl"];
			if (returnUrl != null)
				url = returnUrl;

			// use referrer
			if (url.IsNullOrWhiteSpace())
			{ 
				var urlReferer = context.RequestContext.HttpContext.Request.UrlReferrer;
				if (urlReferer != null)
					url = urlReferer.ToString();
			}

			// use default URL
			if (url.IsNullOrWhiteSpace())
				url = DefaultUrl;

			context.Controller.TempData.Keep();
	
			context.HttpContext.Response.Redirect(url, false);
		}
	}
}
